08. Using AJAX to send data to flask

Using AJAX to send data to flask Heading

Using AJAX to send data to flask

Using AJAX to send data asynchronously

ND004 C01 L05 08 Using AJAX To Send Data To Flask

Takeaways

  • Data request are either synchronous or async (asynchronous)
  • Async data requests are requests that get sent to the server and back to the client without a page refresh.
  • Async requests (AJAX requests) use one of two methods:
    • XMLHttpRequest
    • Fetch (modern way)

Using AJAX to send data to flask Recap

Using XMLHttpRequest

ND004 C01 L05 08.1 Using AJAX To Send Data To Flask

Code

var xhttp = new XMLHttpRequest();

description = document.getElementById("description").value;

xhttp.open("GET", "/todos/create?description=" + description);

xhttp.send();
xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) { 
      // on successful response
      console.log(xhttp.responseText);
    }
};

Using fetch

ND004 C01 L05 08.2 Using AJAX To Send Data To Flask

Takeaways

  • fetch is another window object that lets you send HTTP requests
  • fetch(<url-route>, <object of request parameters>)

Code

fetch('/my/request', {
  method: 'POST',
  body: JSON.stringify({
    'description': 'some description here'
  }),
  headers: {
    'Content-Type': 'application/json'
  }
});

ND004 C01 L05 09 Sending AJAX Requests Using Fetch